package logic

import (
	"context"
	"fmt"
	"vipshop/model/mysql"
	"vipshop/model/redis"
	"vipshop/pkg"

	"vipshop/userrpc/internal/svc"
	"vipshop/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserUpdateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserUpdateLogic {
	return &UserUpdateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserUpdateLogic) UserUpdate(in *userrpc.UserUpdateRequest) (*userrpc.UserUpdateResponse, error) {
	// todo: add your logic here and delete this line

	cmd := redis.Client.Get("sendSmsupdate" + in.Tel)
	if cmd.Val() != in.Sendsmscode {
		return nil, fmt.Errorf("短信验证码不正确，请重新输入")
	}

	var user mysql.User
	mysql.DB.Debug().Model(&mysql.User{}).Where("tel=?", in.Tel).Find(&user)
	if user.ID == 0 {
		return nil, fmt.Errorf("该手机号还没有注册，请重新输入")
	}
	if user.Password != pkg.PwdMD5(in.Password) {
		return nil, fmt.Errorf("旧密码不正确，请重新输入")
	}
	if in.Password == in.Password1 {
		return nil, fmt.Errorf("旧密码与新密码不能一致")
	}
	user.Password = pkg.PwdMD5(in.Password1)

	mysql.DB.Debug().Model(&mysql.User{}).Updates(&user)

	redis.Client.Del("sendSmsupdate" + in.Tel)

	return &userrpc.UserUpdateResponse{Id: int64(user.ID)}, nil
}
